package org.itboys.mobile.controller.weixin;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.entity.mongo.SundayAddress;
import org.itboys.mobile.entity.mysql.order.SundayOrder;
import org.itboys.mobile.service.mongo.front.SundayFrontAddressService;
import org.itboys.mobile.service.mysql.front.SundayFrontOrderService;
import org.itboys.mobile.service.mysql.front.SundayWeiXinPayService;
import org.itboys.mobile.util.ResponseMessage;
import org.itboys.pay.weixin.JsPaySignTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zhangyang
 * 时间：2017年12月18日
 * 描述：圣代_支付_controller_weixin
 */
@Controller
@RequestMapping("/sunday/weixin/pay")
public class SundayWeiXinPayController extends BaseController {
    @Autowired
    private SundayWeiXinPayService payService;
    @Autowired
    private SundayFrontOrderService orderService;

    /**
     * 查询用户所有收货地址并显示在页面
     * @param request
     * @param response
     * @param

     */
    @RequestMapping(value="/index", method={RequestMethod.GET,RequestMethod.POST})
    public String index(
            HttpServletRequest request,
            HttpServletResponse response,Model model,
            @ApiParam(required = true, name = "orderIds", value = "订单ID") @RequestParam(value = "orderIds", required = true) List<Long> orderIds){
        try{
            Map<String,Object> orderPayResult = payService.index(orderIds);
            model.addAttribute("orderPayResult",orderPayResult);
            //2018年1月30日，传入地址
          //  model.addAttribute("addressId",request.getParameter("addressId"));
            return "/aigou/weixin/pay/index";
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/pay/index----e="+e.getMessage());
            }
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }
    /**
     * 微信支付-统一下单
     * @param request
     * @param outTradeNo
     * @param response
     */
    @RequestMapping("/preparePay")
    public  void preparePay(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam(value="outTradeNo",required = true) String outTradeNo){

        try {
            //SundayMemberSessionDto memberSessionDto=AccountIdHoldUtils.getSessionMember(request);
            JsPaySignTool tool=payService.preparePay(request,outTradeNo);
            ResponseMessage.success(tool);
        } catch (Exception e) {
            String msg =CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/pay/preparePay----e="+e.getMessage());

            }
            e.printStackTrace();
        }
    }
    @RequestMapping("/success")
    public String success(
            HttpServletRequest request,
            HttpServletResponse response,Model model,
            @ApiParam(required = false, name = "orderIds", value = "需要支付的订单id集合") @RequestParam(value = "orderIds", required = false) List<Long> orderIds
            ){
        try{
            if(ListUtil.isNotNull(orderIds)){
                Map<String,Object> param = new HashMap<String,Object>();
                param.put("ids",orderIds);
                List<SundayOrder> orders= orderService.select(param);
                Double payAmount = 0.00;
                for(SundayOrder order:orders){
                    payAmount+=order.getPayAmount().doubleValue();
                }
                model.addAttribute("payAmount",new BigDecimal(payAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
                model.addAttribute("receiveName", orders.get(0).getReceiveName());
                model.addAttribute("receiveMobile", orders.get(0).getReceiveMobile());
                model.addAttribute("receiveAddress", orders.get(0).getProvinceName()+orders.get(0).getCityName()+orders.get(0).getDistrictName()+orders.get(0).getReceiveAddress());
            }
           /* if(LongUtil.isNotZreo(orderId)){
                SundayOrder order =orderService.find(orderId);
                model.addAttribute("order",order);
            }*/
            //model.addAttribute("payAmount",payAmount);
            return "/aigou/weixin/pay/success";
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/aigou/weixin/pay/success----e="+e.getMessage());
            }
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }
    @RequestMapping(value="/callback", method = {RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【用户版】微信开发平台支付回掉接口。由微信回掉，移动端忽略。")
    public  void callback(
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        try {
            String reuslt =payService.callback(request, response);
            AjaxUtils.renderJson(response, reuslt);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("/sunday/weixin/pay/callback------"+e.getMessage());
            AjaxUtils.renderJson(response, "fail");
        }
    }
}
